<template>
    <basic-container>
        <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="form"
        >
            <el-row :gutter="20" style="margin-bottom: 10px">
                <el-col :span="6">
                    <el-button
                        size="mini"
                        icon="el-icon-error"
                        @click="close"
                    >关闭</el-button
                    >
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="教室地点">
                        <el-input v-model="form.roomName" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <el-form-item label="会议主题">
                        <el-input v-model="form.subject" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="会议类型">
                        <el-input v-model="form.purposeName" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="参与人数">
                        <el-input v-model="form.userNumber" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="审核状态">
                        <!-- <el-input v-model="form.status | approveStatus" disabled></el-input> -->
                        <el-select v-model="form.status" placeholder="" style="width: 100%" disabled>
                            <el-option :label="item.label" :value="item.value" v-for="item in statusList" :key="item.label"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="申请人">
                        <el-input v-model="form.applicantName" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="申请部门">
                        <el-input v-model="form.deptName" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="开始时间">
                        <el-input v-model="form.beginDate" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结束时间">
                        <!-- <el-input v-model="form.endDate"></el-input> -->
                        <el-date-picker
                        v-model="endDate"
                        :clearable="false"
                        type="date"
                        @change="dateChange"
                        
                        value-format="yyyy-MM-dd"
                        format="yyyy-MM-dd"
                        placeholder="选择日期">
                        </el-date-picker>
                        <el-time-select
                        v-model="endTime"
                        :clearable="false"
                        @change="timeChange"
                        value-format="hh:mm"
                        format="hh:mm"
                        :picker-options="{
                            start: '00:00',
                            step: '00:30',
                            end: '23:00 ',
                            minTime: minStartTime
                        }"
                        placeholder="选择时间">
                        </el-time-select>
                    </el-form-item>
                </el-col>
                
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="完成准备?">
                        <el-button
                            type="primary"
                            size="mini"
                            icon="el-icon-check"
                            @click="submit"
                            >完成</el-button
                        >
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <!-- 表格 -->
        <el-button
            class="add-btn"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="add"
            style="margin-bottom: 15px"
        >
            新增
        </el-button>
        <el-button
            class="add-btn"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeBtn"
            style="margin-bottom: 15px"
            :disabled='chooseCheckBox'
        >
            删除
        </el-button>
        <vxe-table
            border
            resizable
            highlight-hover-row
            show-overflow
            ref="xTable1"
            :data="tableData"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            @checkbox-all="selectAllEvent"
            @checkbox-change="selectChangeEvent"
        >
            <vxe-table-column type="checkbox" width="60" fixed="left"></vxe-table-column>
            <vxe-table-column
                field="materialName"
                title="物料"
            ></vxe-table-column>
            <vxe-table-column
                field="number"
                :edit-render="{autofocus: '.vxe-input--inner'}"
                title="数量/小时"
            >
            <template v-slot:edit="{ row }">
                <vxe-input type="number" min="0.5" :step="row.typeId==0?1:0.5" v-model="row.number" @blur="editNumber(row)" @prev-number="editNumber(row)" @next-number="editNumber(row)"></vxe-input>
            </template>
            </vxe-table-column>
            <vxe-table-column
                field="price"
                title="单价"
            ></vxe-table-column>
            <vxe-table-column
                field="remark"
                title="备注"
                min-width="300"
            ></vxe-table-column>
        </vxe-table>
        <div class="total">
            价格总计: ￥{{totalPrice}}
        </div>
        <!-- <vxe-pager
            :loading="loading"
            :current-page="tablePage.page"
            :page-size="tablePage.size"
            :total="tablePage.totalElements"
            background
            @page-change="handlePageChange"
        >
        </vxe-pager> -->
        <el-dialog
        title="新增物资"
        :visible.sync="dialogVisible" :before-close="reset"
        width="30%">
        <div>
            <el-form ref="model" :model="model" :rules="rules" label-width="80px">
                <el-form-item label="物资" prop="materialId">
                    <el-select v-model="model.materialId" placeholder="请选择物资" style="width: 100%" @change="getPrice">
                        <el-option :label="item.materialName" :value="item.materialId" v-for="item in materialList" :key="item.materialId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="unit" prop="number" v-if="unit ==='数量'"
                :rules="[
                    { required: true, message: `数量不能为空`, trigger: 'blur' },
                ]">
                    <el-input v-model="model.number" onkeyup="value=value.replace(/[^0-9.]/g,'')"></el-input>
                </el-form-item>
                 <el-form-item :label="unit" prop="number" v-if="unit ==='小时'"
                :rules="[
                    { required: true, message: `小时不能为空`, trigger: 'blur' },
                ]">
                    <el-input v-model="model.number" onkeyup="value=value.replace(/[^0-9.]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="price">
                    <el-input v-model="model.price" disabled></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                        type="textarea"
                        :rows="2"
                        placeholder="请输入内容"
                        v-model="model.remark">
                    </el-input>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="reset">取 消</el-button>
            <el-button type="primary" @click="submitMater('model')">确 定</el-button>
        </span>
        </el-dialog>
    </basic-container>
</template>

<script>
import api from "@/api/classroom/classroom";
export default {
    data() {
        return {
            dialogVisible: false,
            labelPosition: "right",
            unit: '数量',
            form: {
                roomName: "",
                subject: "",
                type: "",
                userNumber: ''
            },
            model: {
                materialId: '',
                number: '',
                price: '',
                remark: '',
                status: '',
                
            },
            startDate: '',
            endDate: '',
            minStartTime: '',
            endTime: '',
            materialList: [],
            loading: false,
            tableData: [],
            searchForm: {
                //搜索表单
                typeName: "",
            },
            pickerOptions1: {
                disabledDate(time) {
                    let dateTime = new Date();
                    let startDateTime = dateTime.setDate(dateTime.getDate() - 1);
                    let endDateTime = dateTime.setDate(dateTime.getDate() + 15);
                    return (
                        time.getTime() < new Date(startDateTime).getTime() ||
                        time.getTime() > new Date(endDateTime).getTime()
                    );
                },
            },
            removeIds: [],
            tablePage: {
                total: 0,
                page: 1,
                size: 10,
                background: true,
                totalElements: 0,
            },
            rules: {
                materialId: [
                    { required: true, message: '请选择物资', trigger: 'change' }
                ],
                price: [
                    { required: true, message: '单价不能为空', trigger: 'blur' }
                ],
                number: [
                    { required: true, message: '请输入数量', trigger: 'blur' }
                ]
            },
            statusList: [
                {
                    label: '审核中',
                    value: 2
                },
                {
                    label: '已审核',
                    value: 3
                },
                {
                    label: '已结算',
                    value: 7
                },
                {
                    label: '已拒绝',
                    value: 7
                },
            ]

        };
    },
    computed:{
        chooseCheckBox() {
            return this.removeIds.length ? false : true;
        },
        totalPrice() {
            let materiaTotalPrice = 0;
            if (this.form && this.form.mrRecordDtlDto &&this.form.mrRecordDtlDto.length) {
                this.form.mrRecordDtlDto.forEach((item) => {
                    materiaTotalPrice += item.price*item.number;
                });
            } else {
                materiaTotalPrice = 0;
            }
            
            return this.form.roomCost + materiaTotalPrice;
        }
    },
    mounted() {
        this.getInfo();
        this.getCompList();
    },
    methods: {
        editNumber(data) {
            data.number = this.getNumber(data.number,data.typeId);
            const params = {
                dtlId: data.dtlId,
                number: data.number
            }
            api.queryMaterialSub(params, 'put').then(() => {
                // this.$message({
                //     message: '修改成功！',
                //     type: 'success'
                // });
                //this.getInfo();
            });
        },
        getNumber(number,typeId) {
            if(typeId==0) {
                return Math.ceil(number);
            }else {
                let a = parseInt(number);
                let b = number-a;
                if(b>0 && b<=0.5) {
                    return a+0.5;
                }else if(b==0) {
                    return a;
                }else {
                    return a+1;
                }
            }
        },
        getCompList() {
            const params = {
                materialName: '',
                page: this.tablePage.page,
                size: 1000,
            }
            api.queryMaterialList(params, 'get').then((res) => {
                this.materialList = res.content;
            })
        },
        //重置表单
        reset() {
            this.$refs["model"].resetFields();
            this.dialogVisible = false;
        },
        // 新增
        add() {
            this.dialogVisible = true;
        },
        getPrice(value) {
            let data = this.materialList.filter((item) => {return item.materialId === value});
            let data2 = this.materialList.filter((item) => {return item.materialId === value});
            this.model.price = data[0].materialPrice;
            this.unit = data2[0].typeId==0?'数量':'小时';
        },
        dateChange(value) {
            if (value< this.startDate) {
                this.$message({
                    message: '结束时间不能小于开始时间',
                    type: 'warning'
                });
                return;
            }
            this.startDateChoose();
            this.changeTimeGetPrice();
        },
        timeChange() {
            this.changeTimeGetPrice();
        },
        // 改变结束时间重新获取费用
        changeTimeGetPrice() {
            const params = {
                recordId: this.$route.query.data,
                endDate: `${this.endDate} ${this.endTime}:00`,
            }
            // console.log(`${this.endDate} ${this.endTime}` === this.form.endDate);
            api.queryRoomCost(params, 'get').then((res) => {
                this.form.roomCost = res.roomCost;
            })
        },
        // 删除
        removeBtn() {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.queryMaterialSub(this.removeIds, 'delete').then(() => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getInfo()
            });
            }).catch(() => {
                console.log('已取消')
            });
        },
        submit() {
            if(this.form.beginDate>=`${this.endDate} ${this.endTime}`){
                return this.$message({
                        message: '结束时间不能小于开始时间！',
                        type: 'warning'
                    });
            }
            this.$confirm('确定准备完成了吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const params = {
                    recordId: this.$route.query.data,
                    isReady: 1,
                    roomId: this.form.roomId,
                    beginDate: `${this.form.beginDate}:00`,
                    endDate: `${this.endDate} ${this.endTime}:00`
                };
                api.querySubscribeInfo(params, 'put').then(() => {
                    this.getInfo();
                    this.$message({
                        type: 'success',
                        message: '准备成功!'
                    });
                    this.$router.push({
                        path: '/classroom-manag/reservation-list'
                    });
                    this.$router.$avueRouter.closeTag();
                });
            }).catch(() => {
                console.log('已取消')
            });
        },
        // 根据id 查询具体预约信息
        getInfo() {
            const params = {
                recordId: this.$route.query.data
            };
            api.queryInfoWithId(params, "get").then((res) => {
                this.tableData = res[0].mrRecordDtlDto;
                this.form = res[0];
                this.endTime = this.form.endDate.substring(11, 16);
                this.startDate = this.dealWithTime(this.form.beginDate);
                this.endDate = this.dealWithTime(this.form.endDate);
                this.startDateChoose();
            });
        },
        // 选择开始时间
        startDateChoose() {
            // console.log(this.startDate === this.endDate);
            if (this.startDate === this.endDate) {
                this.minStartTime = this.form.beginDate.substring(11, 16);
            } else {
                this.minStartTime = '';
            }
        },
        dealWithTime(date) {
            let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)[0];
            return newDate;
        },
        // 提交物资
        submitMater(formName) {
            //判断物资是否存在
            let materialList = [];
            this.tableData.forEach(item =>{
                materialList.push(item.materialId);
            })
            if(materialList.includes(this.model.materialId)){
                return this.$message({
                        message: '新增物资已存在！',
                        type: 'warning'
                    });
            }
            this.$refs[formName].validate((valid) => {
            if (valid) {
                const params = {
                    recordId: this.$route.query.data,
                    ...this.model
                };
                api.queryMaterialSub(params, 'post').then((res) => {
                    this.dialogVisible = false;
                    this.getInfo();
                });
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
        handlePageChange({ currentPage, pageSize }) {
            this.tablePage.page = currentPage;
            this.tablePage.size = pageSize;
            this.getCompList();
        },
        // 取消准备
        close() {
            this.$router.push({
                path: '/classroom-manag/reservation-list'
            });
            this.$router.$avueRouter.closeTag();
        },
        selectAllEvent ({ checked, records }) {
            this.removeIds = records.map((item)=>{ return item.dtlId });
        },
        // eslint-disable-next-line no-unused-vars
        selectChangeEvent ({ checked, records }) {
            this.removeIds = records.map((item)=>{ return item.dtlId });
        },
    },
};
</script>

<style lang="scss" scoped>
.total {
    text-align: center;
    height: 45px;
    line-height: 45px;
    background-image: linear-gradient(#e7e7e7, #e7e7e7), linear-gradient(#e7e7e7, #e7e7e7);
    padding-right: 30px;
    font-size: 18px;
    font-weight: 900;
    user-select: none;
}
.el-col {
    margin-bottom: 0;
}
</style>